﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.CommandLineUtilities
{
    public partial class CommandLineEditor : Form, IComponentEditor 
    {
        private object _OwnerActivityNode;
        private CommandLineComponent _CommandLineComponent;

        public CommandLineEditor()
        {
            InitializeComponent();
        }

        private void CommandLineEditor_Load(object sender, EventArgs e)
        {

        }

        public event UpdateComponentSettings UpdateComponentSettingEvent;

        public object OwnerActivityNode
        {
            get { return _OwnerActivityNode; }
            set { _OwnerActivityNode = value; }
        }

        public Type WorkflowComponentType
        {
            get { return typeof(CommandLineComponent); }
        }

        public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents,
                                 object activityNode, WorkflowComponentBase wfComponent)
        {
            this._OwnerActivityNode = activityNode;
            this._CommandLineComponent = (CommandLineComponent) wfComponent;

            this.txt_ExeFilePath.Text = this._CommandLineComponent.ProgramFilePath;
            this.txt_ArgumentExpression.Text = this._CommandLineComponent.ArgTemplate;
            this.dv_Options.Rows.Clear();
            if(this._CommandLineComponent.Options !=null && this._CommandLineComponent.Options.Count>0)
            {
                foreach(string opName in this._CommandLineComponent.Options.Keys)
                {
                    DataGridViewRow dr=new DataGridViewRow();
                    DataGridViewTextBoxCell cellOpName=new DataGridViewTextBoxCell();
                    cellOpName.Value = opName;
                    dr.Cells.Add(cellOpName);

                    DataGridViewTextBoxCell cellOpValue=new DataGridViewTextBoxCell();
                    cellOpValue.Value = this._CommandLineComponent.Options[opName];
                    dr.Cells.Add(cellOpValue);

                    this.dv_Options.Rows.Add(dr);
                }
            }
        }

        public void SaveSettings()
        {
            this._CommandLineComponent.ProgramFilePath = this.txt_ExeFilePath.Text;
            this._CommandLineComponent.ArgTemplate = this.txt_ArgumentExpression.Text;
            this._CommandLineComponent.Options=new Dictionary<string, string>();
            foreach(DataGridViewRow dr in this.dv_Options.Rows)
            {
                if(!dr.IsNewRow  && (dr.Cells[0].Value !=null) && (dr.Cells[1].Value !=null))
                {
                    string key = dr.Cells[0].Value.ToString();
                    string val = dr.Cells[1].Value.ToString();
                    this._CommandLineComponent.Options.Add(key,val);
                }
            }
        }

        public TestResult Test()
        {
            this.SaveSettings();
            try
            {
                Process proc = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = this._CommandLineComponent.ProgramFilePath;
                startInfo.Arguments = this.txt_ArgumentExpression.Text;
                proc.StartInfo = startInfo;
                proc.Start();
                proc.WaitForExit();

                return new TestResult(true, "Succeed");
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());

                return new TestResult(false,ex.Message);
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            if(this.UpdateComponentSettingEvent !=null)
            {
                this.UpdateComponentSettingEvent(this._OwnerActivityNode, this._CommandLineComponent);
            }
            this.Close();
        }

        private void btn_Browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg=new OpenFileDialog();
            dlg.Filter = "Exe files(*.exe)|*.exe|All files(*.*)|*.*";
            if(dlg.ShowDialog()==DialogResult.OK)
            {
                this.txt_ExeFilePath.Text = dlg.FileName;
            }
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            bool exist = false;
            string opName = this.txt_OptionName.Text;
            string opValue = this.txt_OptionValue.Text;
            foreach(DataGridViewRow dr in this.dv_Options.Rows)
            {
                if(!dr.IsNewRow && dr.Cells[0].Value !=null)
                {
                    string key = dr.Cells[0].Value.ToString();
                    if(key.ToLower().Trim()==opName.ToLower().Trim())
                    {
                        exist = true;
                        break;
                    }
                }
            }
            if(!exist)
            {
                DataGridViewRow newDr = new DataGridViewRow();
                DataGridViewTextBoxCell cellName=new DataGridViewTextBoxCell();
                cellName.Value = opName;
                newDr.Cells.Add(cellName);
                DataGridViewTextBoxCell cellValue=new DataGridViewTextBoxCell();
                cellValue.Value = opValue;
                newDr.Cells.Add(cellValue);
                this.dv_Options.Rows.Add(newDr);

                StringBuilder buffer=new StringBuilder();
                if(this.txt_ArgumentExpression.Text.Trim().Length>0)
                {
                    buffer.Append(this.txt_ArgumentExpression.Text.Trim());
                    buffer.Append(" ");
                }
                if(!string.IsNullOrEmpty(opName))
                {
                    buffer.Append(opName + " ");
                }
                if(opValue.IndexOf(" ")>0)
                {
                    buffer.Append("\"" + opValue + "\"");
                }
                else
                {
                    buffer.Append(opValue);
                }
                this.txt_ArgumentExpression.Text = buffer.ToString();
            }
            
        }
    }
}
